package io.bdmc.common.utils;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @Author djw
 * @Description //
 * @Date 2018/9/5 16:16
 */
public class ExcelImport {
 
    /**
     * @param dest 表格文件
     * @param cellLength 一行多少个单元格
     * @return 返回list集合
     * @throws Exception
     */
    public static List<Map<String,String>> read(InputStream fis, String fileEndWith) throws Exception{
        Workbook wookbook = null;
        
       // FileInputStream fis = null;
        int cellType = 1;
        if(fileEndWith.toLowerCase().equals("xls")){
            wookbook = new HSSFWorkbook(fis);//得到工作簿
            cellType = HSSFCell.CELL_TYPE_STRING;
        }else if(fileEndWith.toLowerCase().equals("xlsx")){
            wookbook = new XSSFWorkbook(fis);
            cellType = XSSFCell.CELL_TYPE_STRING;
        }
        fis.close();
        if( wookbook == null)
        return null;
        //得到一个工作表
        Sheet sheet = wookbook.getSheetAt(0);
        //获得数据的总行数
        int totalRowNum = sheet.getLastRowNum();
        //获得数据的总列数
        int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();
        //要获得属性
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = null;
        //获得所有数据
        //从第x行开始获取
        for(int x = 1 ; x <= totalRowNum ; x++){
            map = new HashMap<String,String>();
            //获得第i行对象
            Row row = sheet.getRow(x);
            for(int y=0;y<coloumNum;y++){
                Cell cell = row.getCell(y);
                String strtype = sheet.getRow(0).getCell(y).getStringCellValue();
                if(StringUtils.isEmpty(strtype)){
                    continue;
                }
                if(cell == null){
                    map.put(strtype,"");
                }else{
                    cell.setCellType(cellType);
                    map.put(strtype, cell.getStringCellValue().toString());
                }
            }
            list.add(map);           
        }
        return list;
    }
}
